package com.fxz.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.fxz.common.lang.Result;
import com.fxz.entity.SysUser;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
 import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;

import static com.fxz.common.lang.Const.CAPTCHA_KEY;

@RestController
public class AuthController extends BaseController{

    @Autowired
    Producer producer;

    /**
     * 生成验证码 并将验证码缓存到redis中 key为UUID生成的随机值 value为验证码
     * @return 验证码以及key
     * @throws IOException
     */
    @GetMapping("/captcha")
    public Result captcha() throws IOException {

        //UUID随机生成生成key
        String key = UUID.randomUUID().toString();
        //生成验证码
        String code= producer.createText();
        //根据验证码生成图片
        BufferedImage image = producer.createImage(code);
        //输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //写入IO
        ImageIO.write(image,"jpg",outputStream);

        //把流转为BASE64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //固定格式
        String  str = "data:image/jpeg;base64,";
        //生成的图片的BASE64编码
        String base64Img = str+encoder.encode(outputStream.toByteArray());

        //将key code存到redis 设置缓存时间为2分钟
        redisUtil.hset(CAPTCHA_KEY,key,code,120);

        return Result.succ(
                MapUtil.builder()
                    .put("token",key)
                    .put("captchaImg",base64Img)
                    .build()
        );

    }

    /**
     *  获取用户信息接口
     * @param principal
     * @return 用户信息接口
     */
    @GetMapping("/sys/userInfo")
    public Result userInfo(Principal principal){
        SysUser user = sysUserService.getByUserName(principal.getName());
        return Result.succ(MapUtil.builder()
                .put("id",user.getId())
                .put("username",user.getUsername())
                .put("avatar",user.getAvatar())
                .put("created",user.getCreated())
                .map()
        );
    }
}
